package com.train.dao;

import com.train.pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBC {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps=null;
        ResultSet rs = null;
        List<User> list = new ArrayList<>();

        try {
            //注册驱动(在JDBC4.0之后，就可以不写)
            //Class.forName("com.mysql.cj.jdbc.Driver");
            //连接数据库
            String url="jdbc:mysql://localhost:3306/train";
            String user="root";
            String pwd="20031011LK";
            conn=DriverManager.getConnection(url,user,pwd);
            //获取预编译数据库操作对象（防止SQL注入）
            String sql="select * from user";
            ps=conn.prepareStatement(sql);
            //执行sql语句
            rs=ps.executeQuery();
            //处理查询结果集
            while(rs.next()){
                int id=rs.getInt(1);
                String username = rs.getString(2);
                String password = rs.getString(3);
                String sex = rs.getString(4);
                String phone = rs.getString(5);
                User user1=new User(id,username,password,sex,phone);
                list.add(user1);
                System.out.println(id+","+username+","+password+","+sex+","+phone);
            }
            System.out.println(list);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
